#include <ani.h>
#include <array>
#include <iostream>
#include <vector>


std::string ANIUtils_ANIStringToStdString(ani_env *env,ani_string ani_str){
    ani_size  strSize;
    env->String_GetUTF8Size(ani_str, &strSize);
   
    std::vector<char> buffer(strSize + 1); // +1 for null terminator
    char* utf8_buffer = buffer.data();

    //String_GetUTF8 Supportted by https://gitee.com/openharmony/arkcompiler_runtime_core/pulls/3416
    ani_size bytes_written = 0;
    env->String_GetUTF8(ani_str, utf8_buffer, strSize + 1, &bytes_written);
    
    utf8_buffer[bytes_written] = '\0'; 
    std::string content = std::string(utf8_buffer); 
    return content;
}

void processParameter(ani_env *env, ani_object obj, ani_object para){
    ani_ref perm;
    if(ANI_OK != env->Object_GetFieldByName_Ref(para, "perm", &perm)){
        std::cerr << "Object_GetFieldByName_Ref Faild" << std::endl;
    }

    ani_int level;
    if(ANI_OK != env->Object_GetFieldByName_Int(para, "level", &level)){
        std::cerr << "Object_GetFieldByName_Int Faild" << std::endl;
    }

    auto PermStr = ANIUtils_ANIStringToStdString(env, static_cast<ani_string>(perm));
    std::cout << "para.perm = " << PermStr << " para.level = " << level << std::endl;
}

ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result)
{
    ani_env *env;
    if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) {
        std::cerr << "Unsupported ANI_VERSION_1" << std::endl;
        return ANI_ERROR;
    }

    static const char *className = "ani_typealias.ETSGLOBAL";
   
    ani_class cls;
    if (ANI_OK != env->FindClass(className, &cls)) {
        std::cerr << "Not found '" << className << "'" << std::endl;
        return ANI_ERROR;
    }

    std::array methods = {
        ani_native_function {"processParameter", nullptr, reinterpret_cast<void *>(processParameter)},
    };

    std::cout << "Start bind native methods to '" << className << "'" << std::endl;

    if (ANI_OK != env->Class_BindNativeMethods(cls, methods.data(), methods.size())) {
        std::cerr << "Cannot bind native methods to '" << className << "'" << std::endl;
        return ANI_ERROR;
    };
    std::cout << "Finish bind native methods to '" << className << "'" << std::endl;

    *result = ANI_VERSION_1;
    return ANI_OK;
}